/**
 * 基础框架功能封装
 * 
 * @author zhangpu
 * @date 2012-4-15
 * @version: 1.0.0 
 * @required JQuery EasyUI
 */
(function($) {
	$.extend({
		acooly : {}
	});
	$.extend($.acooly,
			{
				framework : {
					/**
					 * 添加
					 */
					create : function(opts){
						if(opts.entity){
							$.acooly.framework.doCreate(opts.url,"manage_" + opts.entity + "_editform","manage_" + opts.entity + "_datagrid",
									opts.title,opts.top,opts.width,opts.height,opts.reload,opts.onSubmit,opts.onSuccess);
						}else{
							$.acooly.framework.doCreate(opts.url,opts.form,opts.datagrid,
									opts.title,opts.top,opts.width,opts.height,opts.reload,opts.onSubmit,opts.onSuccess);
						}
					},
					
					/**
					 * 执行添加
					 */
					doCreate : function(url,form,datagrid,title,top,width,height,reload,onSubmitCallback,successCallback){
						$('#'+datagrid).datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
						var t = top?top:null;
						var w = width?width:500;
						var h = height?height:'auto';
						var tt = title?title:'添加';
						$('<div/>').dialog({
							href : contextPath + url,
							title : tt,top:t,width : w, height: h, modal : true, iconCls:'icon-save',
							buttons : [ {
								text : '增加', iconCls : 'icon-add',
								handler : function() {
									var d = $(this).closest('.window-body');
									$('#'+form).ajaxSubmit({
										beforeSubmit:function(formData, jqForm, options){
											//如果有回调函数则处理回调函数的验证
											if(onSubmitCallback){
												return onSubmitCallback.call(this,arguments);
											}
											//编辑页面onSubmit方法
											try {
												var defaultFunc = eval(form + "_onSubmit");
												if(defaultFunc && typeof(defaultFunc)=="function"){
													return defaultFunc.call(this,arguments);
												}
											} catch (e) {
												// ig
											}
											//默认easy-ui-validator验证
											return $('#'+form).form('validate'); 											
										},
										success:function(result, statusText){
											try {
												if (result.success) {
													//如果有回调函数则处理回调函数
													if(successCallback){
														successCallback.call(d, result);
													}
													$.acooly.framework.onSaveSuccess(d,datagrid,result,reload);
												}
												if (result.message) {
													$.messager.show({
														title : '提示',
														msg : result.message
													});
												}
											} catch (e) {
												$.messager.alert('提示', e + " DATA: "+ result.toString());
											}											
										}
									});	
								}
							},{
								text : '关闭', iconCls : 'icon-cancel',
								handler : function() {
									var d = $(this).closest('.window-body');
									d.dialog('close');
								}
							} ],
							onClose : function() {
								$(this).dialog('destroy');
							}
						});
					},		
					
					/**
					 * 新增保存成功后，默认的处理：在datagrid的第一行添加该数据，同时关闭窗口。
					 */
					onSaveSuccess : function(dialog, datagrid, result,reload) {
						if(reload){
							$('#' + datagrid).datagrid('reload');
						}else{
							$('#' + datagrid).datagrid('insertRow', {
								index : 0,
								row : result.entity
							});						
						}
						dialog.dialog('destroy')
					},
					
					/**
					 * 编辑
					 */
					edit : function(opts){
						if(opts.entity){
							$.acooly.framework.doEdit(opts.url,opts.id,"manage_" + opts.entity + "_editform","manage_" + opts.entity + "_datagrid",
									opts.title,opts.top,opts.width,opts.height,opts.reload,opts.onSubmit,opts.onSuccess);
						}else{
							$.acooly.framework.doEdit(opts.url,opts.id,opts.form,opts.datagrid,
									opts.title,opts.top,opts.width,opts.height,opts.reload,opts.onSubmit,opts.onSuccess);
						}
					},					
					
					/**
					 * 执行编辑
					 */
					doEdit : function(url,id,form,datagrid,title,top,width,height,reload,onSubmitCallback,successCallback){
						$('#'+datagrid).datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
						var t = top?top:null;
						var w = width?width:500;
						var h = height?height:'auto';
						var tt = title?title:'编辑';
						if(!id || id == ''){
							$.messager.alert('提示', '请选择需要编辑的数据');
							return;
						}
						$('<div/>').dialog({
							href : contextPath + url + "?id=" + id,
							title : tt, top:t,width : w, height: h, modal : true, iconCls:'icon-save',
							buttons : [ {
								text : '修改', iconCls : 'icon-add',
								handler : function() {
									var d = $(this).closest('.window-body');
									$('#'+form).ajaxSubmit({
										beforeSubmit:function(formData, jqForm, options){
											//如果有回调函数则处理回调函数的验证
											if(onSubmitCallback){
												return onSubmitCallback.call(this,arguments);
											}
											//编辑页面onSubmit方法
											try {
												var defaultFunc = eval(form + "_onSubmit");
												if(defaultFunc && typeof(defaultFunc)=="function"){
													return defaultFunc.call(this,arguments);
												}
											} catch (e) {
												// ig
											}
											//默认easy-ui-validator验证
											return $('#'+form).form('validate'); 											
										},
										success:function(result, statusText){
											try {
												if (result.success) {
													//如果有回调函数则处理回调函数
													if(successCallback){
														successCallback.call(d,data);
														return;
													}
													$.acooly.framework.onUpdateSuccess(d,datagrid,result,id,reload);
												}
												if (result.message) {
													$.messager.show({
														title : '提示',
														msg : result.message
													});
												}
											} catch (e) {
												$.messager.alert('提示', e + "DATA: "+ data);
											}											
										}
									});	
								}
							},{
								text : '关闭', iconCls : 'icon-cancel',
								handler : function() {
									var d = $(this).closest('.window-body');
									d.dialog('close');
								}
							} ],
							onClose : function() {
								$(this).dialog('destroy');
							}
						});
					},					
					
					
					/**
					 * 修改更新保存成功后
					 */
					onUpdateSuccess : function(dialog, datagrid, result, id, reload) {
						if(reload){
							$('#' + datagrid).datagrid('reload');
						}else{
							$('#' + datagrid).datagrid('updateRow', {
								index : $('#' + datagrid).datagrid('getRowIndex', id),
								row : result.entity
							});					
						}
						dialog.dialog('destroy')
					},
					
					/**
					 * search
					 * 
					 * @param searchForm
					 * @param datagrid
					 */
					search : function(searchForm, datagrid) {
						var queryParams = serializeObject($('#' + searchForm));
						if(isEmptyObject(queryParams)){
							queryParams = serializeObjectFromContainer($('#' + searchForm));
						}
						$('#' + datagrid).datagrid('load', queryParams);
					},
					
					/**
					 * 按键回车直接执行查询
					 * 
					 * @param searchForm
					 * @param datagride
					 */
					registerKeydown : function(searchForm, datagride) {
						var form = $('#' + searchForm);
						$('input', form).keydown(function(event) {
							if (event.keyCode == 13) {
								$.acooly.framework.search(searchForm, datagride);
							}
						});
					},	

					/**
					 * 查詢并導出數據
					 * 
					 * @param url
					 * @param searchForm
					 * @param fileName
					 */
					exports : function(url, searchForm, fileName,confirmTitle,confirmMessage) {
						var title = confirmTitle?confirmTitle:"导出";
						var message = confirmMessage?confirmMessage:"您确定以当前查询条件导出所有数据？"
						$.messager.confirm(title , message, function(r) {
							if(!r){
								return;
							}
							var queryParams = serializeObject($('#'+ searchForm));
							$(queryParams).attr('exportFileName',fileName)
							$.acooly.framework.createAndSubmitForm(url,queryParams);
						});
					},		
					
					/**
					 * 动态创建表单和提交表单
					 */
					createAndSubmitForm : function(url,inputObjects){
						var form = $('<form action="' + contextPath + url + '" method="POST"></form>');
						for ( var key in inputObjects) {
							if (inputObjects[key] != '') {
								var inputForm = $('<input type="hidden" name="' + key + '" value="' + inputObjects[key] + '" />');
								form.append(inputForm);
							}
						}
						form.appendTo($('body')).submit();
						form.remove();					
					},
					
					/**
					 * show
					 */
					show : function(url, width, height) {
						$('<div/>').dialog({
							href : contextPath + url,
							width : width,
							height : height,
							modal : true,
							title : '查看',
							buttons : [ {
								text : '关闭',
								iconCls : 'icon-cancel',
								handler : function() {
									var d = $(this).closest('.window-body');
									d.dialog('close');
								}
							} ],
							onClose : function() {
								$(this).dialog('destroy');
							}
						});
					},
					
					/**
					 * 创建uploadify上传组件
					 */
					createUploadify:function(options){
						//alert(contextPath + options.url+";jsessionid="+options.jsessionid+"&JSESSIONID="+options.jsessionid);
					    $('#'+options.uploader).uploadify({
					    	'buttonText': '<span style="font-size: 12px;font-weight: normal;">选择文件</span>',
					        'height'    : 22,  
					        'width'     : 80,
					    	'auto'      : false,
					    	'multi'     : false,
					    	'queueSizeLimit' : 1,  
					    	'fileTypeDesc'  : '支持格式:Excel2000和CSV',
					    	'fileTypeExts'  : '*.xls;*.csv',
					    	'fileSizeLimit' :'200MB',
					        'swf'      : '/manage/plugin/jquery-uploadify/uploadify.swf',
					        'uploader' : contextPath + options.url+";jsessionid="+options.jsessionid,
					        'cancelImg'      : '/manage/plugin/jquery-uploadify/uploadify-cancel.png',
					        'successTimeout' : 600,
					        'onUploadSuccess': function(file, data, response) {
					        	var result = $.parseJSON(data);
					        	if(result.success){
					        		$('#'+options.messager).html('导入成功.');
					        	}else{
					        		$('#'+options.messager).html('导入失败:'+result.message);
					        	}
					        	$('#'+options.uploader).uploadify('cancel');
					        },
					        'onUploadError' : function(file, errorCode, errorMsg, errorString) {
					        	$('#'+options.messager).html('导入失败 - [' + errorString + ']');
					        	$('#'+options.uploader).uploadify('cancel');
					        },
					        'onUploadProgress' : function(file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
					        	if(totalBytesUploaded < totalBytesTotal){
					        		$('#'+options.messager).html("正在上传文件: ["+ totalBytesUploaded/1024 + "K/" + totalBytesTotal/1024 + "K]");
					        	}else{
					        		$('#'+options.messager).html("正在保存上传数据...");
					        	}
					        	
					        }
					    });		
					},
					
					imports : function(opts){
						var w = opts.width?opts.width:400;
						var h = opts.height?opts.height:280;
						
						$('<div/>').dialog({
							href : contextPath + opts.url,
							width : w,
							height : h,
							iconCls : 'icon-import',
							modal : true,
							title : '数据导入',
							buttons : [ {
								text : '上传导入',
								iconCls : 'icon-import',
								handler : function() {
									$('#'+opts.uploader).uploadify('upload','*');
								}
							}, {
								text : '关闭',
								iconCls : 'icon-cancel',
								handler : function() {
									var d = $(this).closest('.window-body');
									d.dialog('close');
								}
							} ],
							onClose : function() {
								$('#'+opts.uploader).uploadify('destroy');
								$(this).dialog('destroy');
							}
						});						
					},
					
					
					/**
					 * 提交通过ID方式修改记录各种状态的submit。支持删除，移动，状态变更等
					 */
					confirmSubmit : function(url, id, datagrid, confirmTitle,
							confirmMessage) {
						var title = confirmTitle ? confirmTitle : '确定';
						var message = confirmMessage ? confirmMessage
								: '您是否要提交该操作？';
						$.messager.confirm(title, message, function(r) {
							if (r) {
								$.ajax({
									url : contextPath + url,
									data : {
										id : id
									},
									success : function(result) {
										if (result.success) {
											$('#' + datagrid).datagrid('load');
											$('#' + datagrid).datagrid(
													'uncheckAll').datagrid(
													'unselectAll').datagrid(
													'clearSelections');
										}
										if (result.message) {
											$.messager.show({
												title : '提示',
												msg : result.message
											});
										}
									}
								});
							}
						});
					},

					/**
					 * 排序移动，支持置顶和上移 confirmTitle,confirmMessage 为可选
					 */
					move : function(url, id, datagrid, confirmTitle,
							confirmMessage) {
						$.acooly.framework.confirmSubmit(url, id, datagrid,
								confirmTitle, confirmMessage);
					},

					/**
					 * 删除 置顶ID，多个ID可以使用逗号分割
					 */
					remove : function(url, ids, datagrid, confirmTitle,
							confirmMessage) {
						$.acooly.framework.confirmSubmit(url, ids, datagrid,
								confirmTitle, confirmMessage);
					},

					/**
					 * 批量刪除
					 * 
					 * @param url
					 * @param datagrid
					 */
					removes : function(url, datagrid, confirmTitle,
							confirmMessage) {
						var rows = $('#' + datagrid).datagrid('getChecked');
						var ids = [];
						if (rows.length > 0) {
							for ( var i = 0; i < rows.length; i++) {
								ids.push(rows[i].id);
							}
							$.acooly.framework.remove(url, ids.join(','),
									datagrid, confirmTitle, confirmMessage);
						} else {
							$.messager.show({
								title : '提示',
								msg : '请勾选要删除的记录！'
							});
						}
					},
					logout : function(){
						$.messager.confirm('提醒','确定要注销退出吗？',function(r){  
						    if (r){  
						        window.location.href=contextPath+'/manage/logout.html';
						    }  
						})
					},
					changePassword : function() {
						$('<div/>').dialog({
							href : contextPath+'/manage/system/changePassword.jsp',
							width : 400,
							height : 230,
							modal : true,
							title : '修改密码',
							buttons : [ {
								text : '修改密码',
								iconCls : 'icon-edit',
								handler : function() {
									var d = $(this).closest('.window-body');
									$('#user_changePassword_form').form('submit', {
										onSubmit:function(){
									    	var isValid = $(this).form('validate');
									    	if(!isValid){
									    		return false;
									    	}
									    	//自定义检查合法性
											if($('#system_newPassword').val() != $('#system_confirmNewPassword').val()){
												$.messager.alert('提示', '两次密码输入不一致');
												return false;
											}
											return true;						
										},
										success : function(data) {
											try {
												var result = $.parseJSON(data);
												if (result.success) {
													d.dialog('destroy');
												}
												if(result.message){
													$.messager.show({title : '提示',msg : result.message});	
												}
											} catch (e) {
												$.messager.alert('提示', result);
											}
										}
									});
								}
							} ],
							onClose : function() {
								$(this).dialog('destroy');
							},
							onLoad : function() {
								
							}
						});
					}					

					
				}
			});
})(jQuery);
